﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Skype.Client.Data;

namespace Skype.Client {
	public partial class MainForm : Form {
		#region Fields
		private IExchange ex;
		#endregion
		#region Constructor
		public MainForm() {
			InitializeComponent();
		}
		#endregion
		#region Private
		private void buttonStart_Click(object sender, EventArgs e) {
			this.buttonStart.Enabled = false;
			this.buttonStop.Enabled = true;
			Uri uri = CreateUri();
			if (uri != null) {
				this.ex = new ExchangeService();
				if (this.ex.Start(uri)) {
					this.comboHostname.Enabled = false;
					this.numericPort.Enabled = false;
				} else {
					MessageBox.Show(this,"Unable to start up proxy.","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
				}
			}
		}
		private void buttonStop_Click(object sender, EventArgs e) {
			this.buttonStart.Enabled = true;
			this.buttonStop.Enabled = false;

			if (this.ex != null) {
				this.ex.Stop();
				this.ex = null;

				this.comboHostname.Enabled = true;
				this.numericPort.Enabled = true;
			}
		}
		private void buttonClose_Click(object sender, EventArgs e) {
			
			this.Close();
		}
		private void LoadData() {
			foreach (var host in DataLogic.GetHostnames()) {
				this.comboHostname.Items.Add(host);
			}
			this.numericPort.Value = 6789;
		}
		private Uri CreateUri() {
			if (!String.IsNullOrEmpty(this.comboHostname.Text)) {
				String url = String.Format("http://{0}:{1}/Skype", this.comboHostname.Text, numericPort.Value.ToString("0"));
				return new Uri(url);
			}
			return null;
		}
		private void linkUrl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
			if (this.ex != null && this.buttonStop.Enabled) {
				Uri url = this.CreateUri();
				if (url != null) {
					Process.Start(url.ToString());
				}
			}
		}
		#endregion
		#region Protected
		protected sealed override void OnHandleCreated(EventArgs e) {
			if (!this.DesignMode && LicenseManager.UsageMode == LicenseUsageMode.Runtime) {
				this.LoadData();
			}
			base.OnHandleCreated(e);
		}
		protected sealed override void OnFormClosing(FormClosingEventArgs e) {
			if (!this.DesignMode && LicenseManager.UsageMode == LicenseUsageMode.Runtime) {
				if (this.buttonStop.Enabled) {
					this.buttonStop.PerformClick();
				}
			}
			base.OnFormClosing(e);
		}
		#endregion
		#region Public

		#endregion
	}
}
